<?php
/**
 * Page object.
 * @author Pavel Savchuk
 */
class RCMS_Object_Page_Page extends RCMS_Core_BaseObject
{

	const SHOW_IN_MAIN_MENU = 1;
	
	const SHOW_IN_STATIC_MENU = 2;
	
	const SHOW_IN_NO_MENU = 0;

	const PROTECTED_SIGN = '*';

    /**
     * @var <id> $id is inherited from the parent class
     */
    protected $_model;

    private $_templateId;

    private $_categoryId;

    private $_showInMenu;

    private $_NavName;

    private $_metaDescription;

    private $_metaKeywords;

    private $_headerTitle;

    private $_url;

    private $_h1;

    private $_shortDescription;

    private $_date;

    private $_owner;

    private $_lastUpdate;

    private $_featuredId;

    private $_is404page;

	private $_protected = false;

    private $_bestPractices;

    private $_isCategory;

	private $_order;

	private $_staticOrder;

    private $_weight;

	private $_seosambaRuleId = 0;

	private $_targetedKeyPhrase;

	/**
	 * PR Sculpting silo id
	 *
	 * @var integer
	 */
	private $_siloId = 0;

    /**
     * Constructor
     *
     * Here we should specify object's model and other initial information that we may need
     */
    public function  __construct($pageId = false) {
        $this->_model = new RCMS_Object_Page_PageModel();
        if($pageId) {
            $pageData = $this->_model->selectPageDataById($pageId);
            $this->loadObjectFromArray($pageData);
        }
    }

	public function setSeosambaRuleId($id) {
		$this->_seosambaRuleId = intval($id);
	}

	public function getSeosambaRuleId() {
		return $this->_seosambaRuleId;
	}

	public function setSiloId($id) {
		$this->_siloId = intval($id);
	}

	public function getSiloId() {
		return $this->_siloId;
	}

	/**
	 * Set the page order
	 *
	 * @param integer $order page order
	 */
	public function setStaticOrder($order) {
		$this->_staticOrder = intval($order);
	}

	/**
	 * Get the page order
	 *
	 * @return integer
	 */
	public function getOrder() {
		return $this->_order;
	}

    /**
	 * Set the page order
	 *
	 * @param integer $order page order
	 */
	public function setOrder($order) {
		$this->_order = intval($order);
	}

	public function getProtected() {
		return $this->_protected;
	}

	public function setProtected($protected) {
		$this->_protected = $protected;
	}

	/**
	 * Get the page weight
	 *
	 * @return integer
	 */
	public function getWeight() {
		return $this->_weight;
	}

    /**
	 * Set the page weight
	 *
	 * @param integer $weight page weight
	 */
	public function setWeight($weight) {
		$this->_weight = intval($weight);
	}


	/**
	 * Get the page order
	 *
	 * @return integer
	 */
	public function getStaticOrder() {
		return $this->_staticOrder;
	}

/**
 * @method  returns Id of a page template
 * @return <Integer> _templateId
 */
    public function getTemplateId()
    {
        return $this->_templateId;
    }

/**
 * @method Set page tempalte id value
 * @param <Integer> $_templateId
 * @return <Void>
 */
    public function setTemplateId($_templateId)
    {
        $this->_templateId = $_templateId;
    }

/**
 * @method  returns Id of a page category
 * @return <Integer> _categoryId
 */
    public function getCategoryId()
    {
        return $this->_categoryId;
    }

/**
 * @method Set page category id value
 * @param <Integer> $_categoryId
 * @return <Void>
 */
    public function setCategoryId($_categoryId)
    {
        $this->_categoryId = $_categoryId;
    }

/**
 * @method  returned value means this page is displayed in menu
 * @return <Integer> _inNavMain
 */
    public function getShowInMenu()    {
        return $this->_showInMenu;
    }

/**
 * @method Set value  means that this  page is displayed in menu
 * @param <Integer> $_showInMenu
 * @return <Void>
 */
    public function setShowInMenu($_showInMenu)
    {
        $this->_showInMenu= $_showInMenu;
    }

/**
 * @method Set navigation name
 * @param <String> _NavName
 * @return <Void>
 */
    public function setNavName($_navName)
    {
        $this->_NavName = $_navName;
    }
/**
 * @method  returns navigation name
 * @return <String> _NavName
 */
    public function getNavName()
    {
        return $this->_NavName;
    }

/**
 * @method  returned page meta description
 * @return <String> _metaDescription
 */
    public function getMetaDescription()
    {
        return trim($this->_metaDescription);
    }

/**
 * @method Set value of page meta description
 * @param <String> _metaDescription
 * @return <Void>
 */
    public function setMetaDescription($_metaDescription)
    {
        $this->_metaDescription = trim($_metaDescription);
    }
/**
 * @method  returned page meta keywords
 * @return <String> _metaKeywords
 */
    public function getMetaKeywords()
    {
        return trim($this->_metaKeywords);
    }
/**
 * @method Set value of page meta keywords
 * @param  <String> _metaKeywords
 * @return <Void>
 */
    public function setMetaKeywords($_metaKeywords)
    {
        $this->_metaKeywords = trim($_metaKeywords);
    }
/**
 * @method  returned page header title
 * @return <String> _headerTitle
 */
    public function getHeaderTitle()
    {
        return $this->_headerTitle;
    }
/**
 * @method Set value of page header title
 * @param  <String> _headerTitle
 * @return <Void>
 */
    public function setHeaderTitle($_headerTitle)
    {
        $this->_headerTitle = $_headerTitle;
    }
/**
 * @method  returned page H1 page tag
 * @return <String> _h1
 */
    public function getH1Tag()
    {
        return $this->_h1;
    }
/**
 * @method Set value of page H1 page tag
 * @param  <String> _h1
 * @return <Void>
 */
    public function setH1Tag($_h1)
    {
        $this->_h1 =$_h1;
    }
/**
 * @method  returned page url
 * @return <String> _url
 */
    public function getUrl()
    {
        return $this->_url;
    }
/**
 * @method Set value of page url
 * @param  <String> _url
 * @return <Void>
 */
    public function setUrl($_url)
    {
		 $this->_url = $_url;
    }
/**
 * @method  returned page short description
 * @return <String> _shortDescription
 */
    public function getShortDescription()
    {
        return trim($this->_shortDescription);
    }

/**
 * @method Set value of page short description
 * @param  <String> _shortDescription
 * @return <Void>
 */
    public function setShortDescription($_shortDescription)
    {
        $this->_shortDescription = trim($_shortDescription);
    }

/**
 * @method  returned page creation date
 * @return <Date> _date
 */
    public function getDate()
    {
        return $this->_date;
    }

/**
 * @method Set value of page creation date
 * @param  <Date> _date
 * @return <Void>
 */
    public function setDate($_date)
    {
        $this->_date = $_date;
    }

 /**
 * @method  returned page owner id
 * @return <Integer> _owner
 */
    public function getOwner()
    {
        return $this->_owner;
    }

/**
 * @method Set value of page owner id
 * @param  <Integer> _owner
 * @return <Void>
 */
    public function setOwner($_owner)
    {
        $this->_owner = $_owner;
    }

     /**
 * @method  returned page last update date
 * @return <Date> _lastUpdate
 */
    public function getLastUpdate()
    {
        return trim($this->_lastUpdate);
    }

/**
 * @method Set value of page last upadate date
 * @param  <Date> _lastUpdate
 * @return <Void>
 */
    public function setLastUpdate($_lastUpdate)
    {
        $this->_lastUpdate = trim($_lastUpdate);
    }

/**
 * @method  returned value that means is page is featured
 * @return <Integer> _featured
 */
    public function getFeaturedId()
    {
        return $this->_featuredId;
    }

/**
 * @method Set value that means is page is featured
 * @param  <Integer> _featured
 * @return <Void>
 */
    public function setFeaturedId($_featuredId)
    {
        $this->_featuredId = $_featuredId;
    }

 /**
 * @method  returned value that means is page is 404
 * @return <Integer> _is404page
 */
    public function getIs404Page()
    {
        return $this->_is404page;
    }

/**
 * @method Set value that means is page is 404
 * @param  <Integer> _is404page
 * @return <Void>
 */
    public function setIs404Page($_is404page)
    {
        $this->_is404page = $_is404page;
    }

/**
 * @method  returned value that means is page applied for using seo best practices
 * @return <Integer> _bestPractices
 */
    public function getBestPractices()
    {
        return $this->_bestPractices;
    }

/**
 * @method Set value that means is page applied for using seo best practices
 * @param  <Integer> _bestPractices
 * @return <Void>
 */
    public function setBestPractices($_bestPractices)
    {
        $this->_bestPractices = $_bestPractices;
    }

/**
 * @method  returned value that means is page a category
 * @return <Integer> _isCategory
 */
    public function getIsCategory()
    {
        return $this->_isCategory;
    }

/**
 * @method Set value that means is a category
 * @return <Void>
 */
    public function setIsCategory($_isCategory)
    {
		$this->_isCategory = $_isCategory;
    }

	private function _getParentCategoryId() {
		$parentCatId = $this->_model->getParentCatId($this->_categoryId);
		return $parentCatId['parentId'];
	}

	public function  getTargetedKeyPhrase(){
		return trim($this->_targetedKeyPhrase);
	}

	public function  setTargetedKeyPhrase($targetedKeyPhrase){
		$this->_targetedKeyPhrase = trim($targetedKeyPhrase);
	}


/**
 * @method inherited function. Insert new page in the database
 * @return <Integer> Result of inserting.   1- success 0 - failed.
 */
    public function _insert()
    {
        return $this->_model->inserPage($this);
    }
/**
 * @method inherited function. update existed page in the database
 * @return <Integer> Result of updating.   1- success 0 - failed.
 */
    public function _update()
    {
        return $this->_model->updatePage($this);
    }
/**
 *
 * @method inherited function. delete existed page in the database
 * @return <Integer> Result of deleting.   1- success 0 - failed.
 */
    public function delete()
    {
        if ($this->_url == 'index') { return; }
        if ($this->_id == 0) { return; }
        if (!$this->_getCategoryChildren($this->_categoryId)) {
            $result = $this->_model->deletePage($this->_id);
            if ($result) {
                $this->_deleteDependence();
            }
            return $result;
        }
    }

    /**
     * This method deletes dependence.
     * @return <void>
     */
    private function _deleteDependence()
    {
        $config = unserialize(Zend_Registry::get('config'));
        $imagesArray = $this->_model->selectPageImagesByPageId($this->_id);
        if ($imagesArray) {
            foreach ($imagesArray as $imageObj) {
                $pathImage = $config->website->website->path . 'public/previews/' . $imageObj->name;
                $flagDelete =  RCMS_Tools_FilesystemTools::deleteFile($pathImage);
            }
        }
        $this->deleteAllImages();
        $containersIdArray = $this->_model->selectContainerIdsForPageByPageId($this->_id);
        foreach ($containersIdArray as $container) {
            if ($container['id'] > 0) {
                $this->_model->deleteContentByIdContainer($container['id']);
                $this->_model->deleteContainerDependencies($container['id']);
            }
        }
        $webSiteUrl = $config->website->website->url;
        $this->_model->deleteDeeplinksDependencies($webSiteUrl . $this->_url . '.html');
        $this->_model->deleteContainerByPageId($this->_id);
        $this->_model->deleteCategoryById($this->_categoryId);
        $this->_model->deleteFeaturedAreasByPageId($this->_id);
    }

    private function _getCategoryChildren($categoryId)
    {
        if ($categoryId > 0) {
            $category = $this->_model->selectCategoryById($categoryId);
            if ($category->id_parent == 0) {
                $result = $this->_model->selectAllCategories($categoryId);
                if ($result) {
                    return $result;
                }
                return false;
            }
            return false;
        }
        return false;
	}
    
    /**
     * @method inherited function. Insert new page in the database
     * @param  <Array> $pageData
     * @return <Void>
     */
    public function loadObjectFromArray($pageData)
    {
        
        if($pageData){
            foreach ($pageData as $data) {
                $this->setId( (isset($data['id'])) ? $data['id'] :  0 );//inherited.
                //$this->setH1Tag(($data['h1']) ? RCMS_Tools_FilesystemTools::trimInternalSpaces(trim($data['h1'])) :  "");
				$this->setH1Tag($data['h1']);
                //$this->setHeaderTitle(($data['header_title']) ? RCMS_Tools_FilesystemTools::trimInternalSpaces(trim($data['header_title'])) :  "");
				$this->setHeaderTitle(($data['header_title']) ? $data['header_title'] :  "");
                $this->setUrl($this->proccessUrl(($data['url']) ? urldecode($this->proccessUrl(RCMS_Tools_FilesystemTools::trimInternalSpaces(trim($data['url'])))) :  ""));
				//$this->setUrl($data['url'] ? trim($data['url']) :  "");
                //$this->setNavName(($data['nav_name']) ? RCMS_Tools_FilesystemTools::trimInternalSpaces(trim($data['nav_name'])) :  "");
				$this->setNavName(($data['nav_name']) ? $data['nav_name'] :  "");
                $this->setMetaDescription(($data['meta_description']) ? trim($data['meta_description']) :  "");
                $this->setMetaKeywords(($data['meta_keywords']) ? trim($data['meta_keywords']) :  "");
                $this->setShortDescription(($data['short_description']) ? trim($data['short_description']) : "");
                $this->setIs404Page((isset($data['is_404page'])) ? $data['is_404page'] : 0);
				$this->setProtected((isset($data['protected'])) ? $data['protected'] : 0);
                $this->setTemplateId((isset($data['template_id'])) ? $data['template_id'] :  0);
                $this->setCategoryId((isset($data['category_id'])) ? $data['category_id'] :  0);
                $this->setBestPractices(isset($data['bestpractices']) ? trim($data['bestpractices']) : 0);
                $this->setDate((isset($data['date']))? $data['date'] : '0000-00-00 00:00:00' );
                $this->setOwner((isset($data['owner'])) ? $data['owner'] :  0);
                $this->setLastUpdate((isset($data['last_update'])) ? $data['last_update'] : '0000-00-00 00:00:00');
                $this->setShowInMenu(isset($data['show_in_menu']) ? $data['show_in_menu'] :  0);
				$this->setOrder(isset($data['order']) ? $data['order'] : "");
				$this->setStaticOrder(isset($data['static_order']) ? $data['static_order'] : 100);
				$this->setIsCategory(($this->_getParentCategoryId() == 0) ? true : false);
                $this->setWeight(isset($data['weight']) ? $data['weight'] : 0);
				$this->setSiloId(isset($data['silo_id']) ? $data['silo_id'] : 0);
				
				if(isset($data['targeted_key_phrase']) && !empty($data['targeted_key_phrase'])){
					
					$this->setTargetedKeyPhrase(trim($data['targeted_key_phrase']));
				}else{
					$this->setTargetedKeyPhrase($this->getUrl());
				}
            }
        }
    }
/*
	 public function loadObjectFromArray($pageData)
    {

        if($pageData){
            foreach ($pageData as $data) {
                $this->setId( (isset($data['id'])) ? $data['id'] :  0 );//inherited.
                //$this->setH1Tag(($data['h1']) ? RCMS_Tools_FilesystemTools::trimInternalSpaces(trim($data['h1'])) :  "");
				$this->setH1Tag($data['h1']);
                $this->setHeaderTitle(($data['header_title']) ? $data['header_title'] :  "");
                $this->setUrl($this->proccessUrl(($data['url']) ? urlencode($this->proccessUrl($data['url'])) :  ""));
				//$this->setUrl($data['url'] ? trim($data['url']) :  "");
                $this->setNavName(($data['nav_name']) ? $data['nav_name'] :  "");
                $this->setMetaDescription(($data['meta_description']) ? trim($data['meta_description']) :  "");
                $this->setMetaKeywords(($data['meta_keywords']) ? trim($data['meta_keywords']) :  "");
                $this->setShortDescription(($data['short_description']) ? trim($data['short_description']) : "");
                $this->setIs404Page((isset($data['is_404page'])) ? $data['is_404page'] : 0);
                $this->setTemplateId((isset($data['template_id'])) ? $data['template_id'] :  0);
                $this->setCategoryId((isset($data['category_id'])) ? $data['category_id'] :  0);
                $this->setBestPractices(isset($data['bestpractices']) ? trim($data['bestpractices']) : 0);
                $this->setDate((isset($data['date']))? $data['date'] : '0000-00-00 00:00:00' );
                $this->setOwner((isset($data['owner'])) ? $data['owner'] :  0);
                $this->setLastUpdate((isset($data['last_update'])) ? $data['last_update'] : '0000-00-00 00:00:00');
                $this->setShowInMenu(isset($data['show_in_menu']) ? $data['show_in_menu'] :  0);
				$this->setOrder(isset($data['order']) ? $data['order'] : "");
				$this->setStaticOrder(isset($data['static_order']) ? $data['static_order'] : 100);
				$this->setIsCategory(($this->_getParentCategoryId() == 0) ? true : false);
                $this->setWeight(isset($data['weight']) ? $data['weight'] : 0);
				$this->setSiloId(isset($data['silo_id']) ? $data['silo_id'] : 0);
            }
        }
    }
*/

/**
 * @method proccess Url to '-'
 * @param  <String> $search, <String> $replace
 * @return <String> ''
 */
    public function proccessUrl($url,$search=' ',$replace='-')  {
      	$url = str_replace(".html", '',trim($url));
        return str_replace($search, $replace,$url);
    }


	public function setParentCategory($parentCatId) {
		$this->_model->setParentCategory($this->getCategoryId(), $parentCatId);
	}

	public function getParentCategoryId() {
		$result = $this->_model->getParentCatId($this->_categoryId);
		return $result['parentId'];
	}

	public function getParentCategoryName() {
		$parentCatId = $this->getParentCategoryId();
		return $this->_model->selectParentCategoryName($parentCatId);
	}

    public function resetToDefaultTemplate($idDeletedTemplate)
    {
        if($idDeletedTemplate)
        {
            if ($this->_model->updateToDefaultTemplate($idDeletedTemplate)) {
                return true;
            }
            return false;
        }
    }

    public function deleteAllImages()
    {
        return $this->_model->deleteImages($this->getId());
    }

}
